package com.guyaning.deyson_ec.ec.main.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guyaning.deyson_core.core.ui.recycler.DataConverter;
import com.guyaning.deyson_core.core.ui.recycler.ItemType;
import com.guyaning.deyson_core.core.ui.recycler.MultipleFields;
import com.guyaning.deyson_core.core.ui.recycler.MultipleItemBean;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/6/6.
 */

public class IndexDataConverter extends DataConverter {

    @Override
    public ArrayList<MultipleItemBean> convert() {

        final JSONArray jsonArray = JSON.parseObject(getJson()).getJSONArray("data");

        final int size = jsonArray.size();

        for (int i = 0; i < size; i++) {

            final JSONObject data = jsonArray.getJSONObject(i);

            final String imageUrl = data.getString("imageUrl");

            final String text = data.getString("text");

            final int id = data.getInteger("goodsId");

            final int spanSize = data.getInteger("spanSize");

            final JSONArray banners = data.getJSONArray("banners");

            final ArrayList<String>  bannerImages = new ArrayList<>();

            int type = 0;

            if(text!=null && imageUrl == null){
                type = ItemType.TEXT;
            }else if(text == null && imageUrl!=null){
                type = ItemType.IMAGE;
            }else if(imageUrl!=null){
                type = ItemType.IMAGE_TEXT;
            }else if(banners!=null){
                type = ItemType.BANNERS;

                final int bannerSize = banners.size();

                for (int j = 0; j <bannerSize ; j++) {
                    final String banner = banners.getString(j);
                    bannerImages.add(banner);
                }
            }

            final MultipleItemBean bean = MultipleItemBean.builder()
                    .setField(MultipleFields.ITEM_TYPE,type)
                    .setField(MultipleFields.BANNERS,bannerImages)
                    .setField(MultipleFields.ID,id)
                    .setField(MultipleFields.IMAGE_URL,imageUrl)
                    .setField(MultipleFields.SPAN_SIZES,spanSize)
                    .setField(MultipleFields.TEXT,text)
                    .build();

            BEANS.add(bean);

        }

        return BEANS;
    }
}
